package com.yange.accountbook.ui

import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.AttachPopupView
import com.yange.accountbook.R

import com.yange.accountbook.databinding.HomeActivityLayoutBinding
import com.yange.accountbook.entity.BooksEntity
import com.yange.accountbook.entity.IconEntity
import com.yange.accountbook.events.AccountDetailChangeEvent
import com.yange.accountbook.net.Api
import com.yange.accountbook.net.BaseResponse
import com.yange.accountbook.net.api.RetrofitClient
import com.yange.accountbook.net.observable.RecObserver
import com.yange.accountbook.popup.IconPopup

import com.yange.accountbook.ui.adapter.BookListAdapter
import com.yange.accountbook.utils.StringUtils
import com.yange.accountbook.utils.copyStr
import com.yange.accountbook.utils.showToast
import com.yanzhenjie.recyclerview.SwipeMenuCreator
import com.yanzhenjie.recyclerview.SwipeMenuItem
import com.yanzhenjie.recyclerview.touch.OnItemMoveListener
import com.zhuangku.app.widget.EmptyView
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*


class BookFragment : BaseFragment<HomeActivityLayoutBinding>() {

    lateinit var myAdapter: BookListAdapter

    override fun initView() {
        myAdapter = BookListAdapter()
        myAdapter.setEmptyView(activity?.let { EmptyView(it) }!!)

        initListener()

        binding.listBook.layoutManager = LinearLayoutManager(activity)
        binding.listBook.adapter = myAdapter
        refreshBookData()

        EventBus.getDefault().register(this)
    }

    override fun initData() {}

    //监听明细变化，刷新账本总金额
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAccountDetailChange(event: AccountDetailChangeEvent) {
        refreshBookData()
    }

    private fun initListener() {
        binding.titleBar.tvBack?.visibility = View.GONE


        myAdapter.addChildClickViewIds(R.id.layout_book_icon)
        myAdapter.setOnItemChildClickListener { adapter, view, position ->
            //修改
            var item = adapter.getItem(position) as BooksEntity
            if (view.id == R.id.layout_book_icon) {
                XPopup.Builder(context)
                    .asCustom(context?.let {
                        IconPopup(it, object : IconPopup.AddListener {
                            override fun success(icon: IconEntity) {
                                update(icon.icon, icon.name, icon.bizId)
                            }
                        }, IconEntity(item.icon, item.name, item.id))
                    })
                    .show()

            } else {
                //跳转到账本详情
                activity?.let { BookDetailActivity.start(it, item) }
            }
        }

        myAdapter.setOnItemClickListener { adapter, view, position ->
            var item = adapter.getItem(position) as BooksEntity
            activity?.let { BookDetailActivity.start(it, item) }
        }

        //复制账本CODE
        myAdapter.setOnItemLongClickListener { adapter, view, position ->
            var item = adapter.getItem(position) as BooksEntity

            activity?.let { copyStr(it, item.code) }

            true
        }
        //新增账本
        binding.titleBar.tvForward?.setOnClickListener {
            val attachPopupView: AttachPopupView = XPopup.Builder(context)
                .hasShadowBg(false)
                .isViewMode(true)
                .isClickThrough(true)
                .atView(binding.titleBar.tvForward) // 依附于所点击的View，内部会自动判断在上方或者下方显示
                .asAttachList(
                    arrayOf("新增", "通过账本码添加"),
                    intArrayOf(),
                    { position, text ->
                        when (position) {
                            0 -> {
                                XPopup.Builder(activity)
                                    .asCustom(activity?.let { it1 ->
                                        IconPopup(it1, object : IconPopup.AddListener {
                                            override fun success(icon: IconEntity) {
                                                commit(icon.icon, icon.name)
                                            }
                                        }, IconEntity())
                                    })
                                    .show()
                            }
                            1 -> {
                                XPopup.Builder(activity)
                                    .asInputConfirm(
                                        "新增", "请输入账本码"
                                    ) {
                                        addBookByCode(it)
                                    }
                                    .show()
                            }
                        }
                    },
                    0,
                    0 /*, Gravity.LEFT*/
                )
            attachPopupView.show()
        }

        //新增明细
        binding.tvAdd.setOnClickListener {
            activity?.let { it1 -> AddItemActivity.start(it1) }
        }

        //下拉刷新
        binding.smartRefresh.setOnRefreshListener {
            refreshBookData()
        }

        //排序
        initItemMoveListener()

        //删除账本
        initItemSwipeListener()

    }

    fun initItemMoveListener() {
        binding.listBook.isLongPressDragEnabled = true
        binding.listBook.setOnItemMoveListener(object : OnItemMoveListener {
            override fun onItemMove(
                srcHolder: RecyclerView.ViewHolder?,
                targetHolder: RecyclerView.ViewHolder?
            ): Boolean {
                // 此方法在Item拖拽交换位置时被调用。
                // 第一个参数是要交换为之的Item，第二个是目标位置的Item。
                // 交换数据，并更新adapter。
                val fromPosition = srcHolder!!.adapterPosition
                val toPosition = targetHolder!!.adapterPosition
                Collections.swap(myAdapter.data, fromPosition, toPosition)
                myAdapter.notifyItemMoved(fromPosition, toPosition)
                //这里先改本地数据，然后再悄悄该后台数据，不然操作不流畅
                changeSort()
                // 返回true，表示数据交换成功，ItemView可以交换位置。
                return true
            }

            override fun onItemDismiss(srcHolder: RecyclerView.ViewHolder?) {}
        })
    }

    fun initItemSwipeListener() {
        var swipeMenuCreator =
            SwipeMenuCreator { leftMenu, rightMenu, position ->
                var deleteItem = SwipeMenuItem(context)
                deleteItem.height = ViewGroup.LayoutParams.MATCH_PARENT
                deleteItem.width = 200
                deleteItem.textSize = 12
                deleteItem.setBackground(com.yange.accountbook.R.color.my_red)
                context?.getColor(com.yange.accountbook.R.color.text_white).let {
                    it?.let { it1 ->
                        deleteItem.setTextColor(
                            it1
                        )
                    }
                }
                deleteItem.text = "删除"
                rightMenu?.addMenuItem(deleteItem)
            }
        binding.listBook.setSwipeMenuCreator(swipeMenuCreator)
        binding.listBook.setOnItemMenuClickListener { menuBridge, adapterPosition ->
            menuBridge?.closeMenu()
            // 左侧还是右侧菜单：
            val direction = menuBridge!!.direction
            // 菜单在Item中的Position：
            val menuPosition = menuBridge.position
            if (direction == -1 && menuPosition == 0) {
                XPopup.Builder(context)
                    .autoOpenSoftInput(true)
                    .dismissOnTouchOutside(true)
                    .asConfirm(
                        "提示", "确认删除该账本吗"
                    ) {
                        deleteBook(myAdapter.data[adapterPosition].id)
                    }
                    .show()

            }
        }
    }


    fun changeSort() {
        RetrofitClient.getInstance().bookSort(
            activity, Api.BOOK_BOOK_SORT,
            myAdapter.data as java.util.ArrayList<BooksEntity>?
        ).subscribe(object : RecObserver<BaseResponse<Any>>(activity, false, false) {
            override fun onSuccess(t: BaseResponse<Any>?) {
            }

            override fun onFail(msg: String, code: Int) {
            }
        })
    }


    private fun deleteBook(id: Int) {
        var arrayList = ArrayList<Int>()
        arrayList.add(id)
        RetrofitClient.getInstance().deleteRecord(activity, Api.BOOK_BOOK_DELETE, arrayList)
            .subscribe(object : RecObserver<BaseResponse<Any>>(activity, true, false) {
                override fun onSuccess(t: BaseResponse<Any>?) {
                    showToast("删除成功")
                    refreshBookData()
                }

                override fun onFail(msg: String, code: Int) {
                    showToast(msg)
                }
            })
    }


    //账本页面数据
    private fun refreshBookData() {
        getBookTotalMoney()
        getBookList()
    }

    //获取账本总金额
    private fun getBookTotalMoney() {
        RetrofitClient.getInstance().invokeGet(activity, Api.BOOK_TOTAL_MONEY)
            .subscribe(object : RecObserver<BaseResponse<Double>>(activity, true, false) {
                override fun onSuccess(t: BaseResponse<Double>?) {
                    binding.titleBar.setTitle(StringUtils.buildMoneyTitleBar("钱罐", t?.data!!))
                }

                override fun onFail(msg: String, code: Int) {
                    showToast(msg)
                }
            })
    }

    fun update(icon: String, name: String, id: Int) {
        RetrofitClient.getInstance().invokePostBody(
            context, Api.BOOK_UPDATE, mapOf(
                "id" to id,
                "icon" to icon,
                "name" to name
            )
        ).subscribe(object : RecObserver<BaseResponse<Any>>(context, true, false) {
            override fun onSuccess(t: BaseResponse<Any>?) {
                getBookList()
            }

            override fun onFail(msg: String, code: Int) {
                showToast(msg)
            }

        })
    }

    //新建账本
    private fun commit(icon: String, name: String) {
        RetrofitClient.getInstance().invokePostBody(
            activity, Api.BOOK_SAVE, mapOf(
                "icon" to icon,
                "name" to name
            )
        ).subscribe(object : RecObserver<BaseResponse<Any>>(activity, true, false) {
            override fun onSuccess(t: BaseResponse<Any>?) {
                getBookList()
            }

            override fun onFail(msg: String, code: Int) {
                showToast(msg)
            }

        })
    }


    //新建账本
    private fun addBookByCode(code: String) {
        RetrofitClient.getInstance().addBookByCode(
            activity, code
        ).subscribe(object : RecObserver<BaseResponse<Any>>(activity, true, false) {
            override fun onSuccess(t: BaseResponse<Any>?) {
                getBookList()
            }

            override fun onFail(msg: String, code: Int) {
                showToast(msg)
            }

        })
    }

    /**
     * 获取账本详情
     */
    private fun getBookList() {
        RetrofitClient.getInstance().invokeGet(activity, Api.BOOK_LIST, mapOf())
            .subscribe(object :
                RecObserver<BaseResponse<List<BooksEntity>>>(activity, false, false) {
                override fun onSuccess(t: BaseResponse<List<BooksEntity>>?) {
                    binding.smartRefresh.finishRefresh()
                    myAdapter.setNewInstance(t?.data as MutableList<BooksEntity>?)
                }

                override fun onFail(msg: String, code: Int) {
                    binding.smartRefresh.finishRefresh()
                    showToast(msg)
                }
            })
    }
}